//
//  PreorderPayViewController.swift
//  ShareCar
//
//  Created by 李帅 on 2019/2/18.
//  Copyright © 2019 changqingkeji. All rights reserved.
//

import UIKit

class PreorderPayViewController: UIViewController, SegueHandlerType {
    
    enum SegueIdentifier: String {
        case cancelSegue
    }

    @IBOutlet weak var BigPreAmountLabel: UILabel!
    
    @IBOutlet weak var preAmountLabel: UILabel!
    
    @IBOutlet weak var carTypeNameLabel: UILabel!
    
    @IBOutlet weak var useCarTimeLabel: UILabel!
    
    @IBOutlet weak var useCarAddressLabel: UILabel!
    
    @IBOutlet var paySwith: PaySwith!
    
    @IBOutlet weak var preorderPayLabel: UILabel!
    
    @IBOutlet weak var orderTimeLabel: UILabel!
    
    var name: String?
    
    var address: String?
    
    var createData: Preorder.Create?
    
    var timer: Timer?
    
    var useCarTime: TimeInterval = 0.0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if let c = createData {
            paySwith.balance = c.balanceFlag == 1
        }
        
        preorderPayLabel.text = slipViewController?.config?.preorderPay
        
        paySwith.addObserve { [weak self] payment, success in
            switch payment {
            case .aliPay:
                if success {
                    self?.jumpDetail()
                } else {
                    XHProgressHUD.showError("你取消了支付")
                }
            case .wePay:
                if success {
                    self?.jumpDetail()
                } else {
                    XHProgressHUD.showError("你已取消支付")
                }
            case .balance, .ticket:
                break
            }
        }
        
        guard let data = createData else {
            return
        }
        
        let time = Date(timeIntervalSince1970: TimeInterval(useCarTime))
        
        BigPreAmountLabel.text = createData?.preorderAmount
        preAmountLabel.text = createData?.preorderAmount
        carTypeNameLabel.text = name
        useCarTimeLabel.text = Date.dateConvertString(date: time)
        useCarAddressLabel.text = address
        
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
            DispatchQueue.global().async {
                let now = Date().timeIntervalSince1970
                var time = Int(now) - data.createdTime
                time = 15 * 60 - (time < 0 ? 0 : time)
                let m = time / 60 > 9 ? "\(time / 60)" : "0\(time / 60)"
                let s = time % 60 > 9 ? "\(time % 60)" : "0\(time % 60)"
                DispatchQueue.main.async { [weak self] in
                    
                    self?.orderTimeLabel.text = "\(m):\(s)"
                    if time <= 0 {
                        self?.navigationController?.popViewController(animated: true)
                    }
                }
            }
        }
        
    }
    
    deinit {
        timer?.invalidate()
        timer = nil
    }
    
    func jumpDetail() {
        weak var nav = navigationController
        nav?.popToRootViewController(animated: false)
        let sb = UIStoryboard(name: "Preorder", bundle: nil)
        let vc = sb.instantiateViewController(withIdentifier: "PreorderDetail")
        if let vc = vc as? PreorderDetailViewController {
            vc.preorderId = createData?.preorderId
        }
        nav?.pushViewController(vc, animated: true)
    }
    
    @IBAction func cancel(_ sender: UIBarButtonItem) {
        performSegue(.cancelSegue, sender: nil)
    }
    
    @IBAction func submit(_ sender: UIButton) {
        
        guard let id = createData?.preorderId else {
            return
        }
        
        guard let payment = paySwith.selected else {
            return
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        Preorder.pay(preorderId: id, payment: payment, success: { [weak self] data in
            JZLoading.hideLoading()
            if let payStr = data?.payStr, let self = self {
                switch payment {
                case .aliPay:
                    Pay.zhifuPay(payStr: payStr)
                case .wePay:
                    Pay.wechatPay(payStr: payStr)
                case .balance:
                    XHProgressHUD.showSuccess("支付成功")
                    self.jumpDetail()
                case .ticket:
                    XHProgressHUD.showSuccess("支付成功")
                    self.jumpDetail()
                }
            }
        }) { [weak self] msg in
            JZLoading.hideLoading()
            self?.showError(msg)
        }
    }
    
    // MARK: - Navigation
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        switch segueIdentifier(forSegue: segue) {
        case .cancelSegue:
            if let vc = segue.destination as? PreorderCancelViewController {
                vc.preorderId = createData?.preorderId
            }
        }
    }
}
